<template>
  <Container class="brand-list">
    <div class="container-header title title-center" slot="header">
      {{ title }}
      <Button size="large" class="fl btn-back" icon="ios-arrow-back" @click="jumpPrevPage">返回</Button>
    </div>
    <div class="bgs">
      <Form :model="form" :label-width="80" ref="form" class="form" :rules="rules">
        <FormItem :label-width='20'> 
              <div class="common-class">
                <i class="ivu-icon ivu-icon-ios-alert"></i>
                <span>提示：1、政策内包含的经销商发货给政策内其他经销商下属门店不算串货
                2、政策内包含的经销商下属门店相互之间可以调拨</span>
                </div>
            </FormItem>
        <FormItem label="政策名称" prop="name">
          <Input class="input-name"  clearable :maxlength="20" v-model="form.name" placeholder="请输入政策名称"/>
        </FormItem>
           
        <Input search   clearable v-model="searchContent" style="width:300px; margin-left:80px "   @on-search="onSearchBtnClick(warning)" enter-button placeholder="请输入经销商名称搜索" />
      </Form>
      <div class="all-contents">
        <div class="left-content">
          <Tabs v-model="tab">
            <TabPane>
              <Table
                stripe
                border
                :columns="list.columns"
                :data="changeListNotSelect"
                no-data-text="亲，没有找到相关记录哦！~"
              ></Table>
              <div class="pager">
                <Page
                  :total="list.totalItem"
                  :current="list.currentPage"
                  :page-size="list.pageSize"
                  @on-change="onPageChange"
                  @on-page-size-change="onPageSizeChange"
                  show-sizer
                  placement="top"
                ></Page>
              </div>
              <Loader :status="list.status" @refresh="getDistributorData"></Loader>
            </TabPane>
          </Tabs>
        </div>
        <div class="right-content">
          <Tabs v-model="tab">
            <TabPane>
              <Table
                stripe
                border
                :columns="listData.columns"
                :data="hasListWithSelect"
                no-data-text="亲，没有找到相关记录哦！~"
              ></Table>
            </TabPane>
          </Tabs>
        </div>
      </div>
    </div>
    <div class="container-footer bg-white" slot="footer">
      <div>
        <Button type="primary" class="mr" size="large" :disabled="btnDisabled" @click="onSave">保存</Button>
        <Button type="primary" class="mr" size="large" @click="cancle">取消</Button>
      </div>
    </div>
  </Container>
</template>
<script>
import table from "@/table";
import listData from "./edit/BunchEditItemData";
import bunchEdit from "./edit/bunchEdit";
import { clearEmpty } from "@/util";
import data from "../invalidGoods/list/InvalidGoodsListData";
export default {
  data() {
    return {
      id: this.$route.query.id || "",
      distributorId: "",
      btnDisabled: false,
      title: "新增政策",
      currentIndex: -1,
      searchContent:'',
      rules: {
        name: [{ required: true, message: "政策名称不能为空", trigger: "blur" }]
      },
      form: {
        name: ""
      },
      list: bunchEdit,
      listData: listData
    };
  },
  mounted() {
    if (this.id) {
      this.title = "编辑政策";
      this.getInfo();
    } else {
      this.listData.data = [];
      this.title = "新建政策";
    }
    this.$bus.$on("add", this.add);
    this.$bus.$on("delete", this.delete);
    this.getDistributorData();
  },
  computed: {
    changeListNotSelect() {
      return this.list.data.filter(e => !e.checked);
    },
    hasListWithSelect() {
      return this.listData.data;
    }
  },
  methods: {
    getDistributorData() {
      let param = {
        current: this.list.currentPage,
        size: this.list.pageSize,
        distributorName: this.searchContent
      };
      param = clearEmpty(param);
      this.list.status = "loading";
      this.$ajaxGet("/distributor/contract/pageSignedDistributor", param)
        .then(data => {
          this.list.data = (data.records || []).map(item => {
            let target = {
              distributorName: item.distributorName,
              distributorId:    (item.distributorId).toString()
            };
            return target;
          });
          this.list.totalItem = Number(data.total);
          this.list.status = "pass";
        })
        .catch(() => {
          this.list.status = "error";
        });
    },
     onSearchBtnClick() {
       this.getDistributorData()
     
    },
    getInfo() {
      this.status = "loading";
      this.$ajaxGet(`/setting/scancode_special_policy/detail/${this.id}`)
        .then(data => {
          this.form.name = data.policyName;
          this.listData.data = data.scancodeSpecialPolicyItems.map(it => {

            let target = {
              distributorId: (it.distributorId).toString(),
              distributorName: it.distributorName || "--",
              checked: true
            };
            return target;
          });
          this.status = "pass";
        })
        .catch(() => {
          this.status = "error";
        });
    },
    delete(row) {
      this.listData.data.forEach((v, index) => {
        if (v.distributorId == row.distributorId) {
          this.listData.data.splice(index, 1);
        }
      });
      let idx = this.list.data.findIndex(
        e => e.distributorId == row.distributorId
      );
      if (idx > -1) {
        row.checked = false;
        this.$set(this.list.data, idx, row);
      }
    },
    add(index, row) {
      let rightItem = this.listData.data.find(
        e => e.distributorId == row.distributorId
      );
      if (rightItem) {
        this.$Message.error("已经存在该经销商，请不要重复添加！");
        this.btnDisabled= false
        return;
      } else {
        let idx = this.list.data.findIndex(
          e => e.distributorId == row.distributorId
        );
        row.checked = true;
        this.$set(this.list.data, idx, row);
        this.listData.data.push(row);
      }
    },
    onPageChange(number) {
      this.list.currentPage = number;
      this.$router.push({
        name: "policy/bunch/edit",
        query: {
          currentPage: this.list.currentPage,
          pageSize: this.list.pageSize
        }
      });
      this.getDistributorData();
    },
    onPageSizeChange(pageSize) {
      this.list.currentPage = 1;
      this.list.pageSize = pageSize;
      this.$router.push({
        name: "policy/bunch/edit",
        query: {
          currentPage: this.list.currentPage,
          pageSize: this.list.pageSize
        }
      });
      this.getDistributorData();
    },
    onSave() {
      if (this.btnDisabled) return;
      this.btnDisabled = true;
      this.$refs["form"].validate(valid => {
        if (valid) {
          let text = this.id ? "编辑" : "新增";
          let url = this.id
            ? "/setting/scancode_special_policy/modify"
            : "/setting/scancode_special_policy/save";
          let arr = this.hasListWithSelect.map(it => {
            return {
              distributorId: it.distributorId
            };
          });
          let param = {
            policyName: this.form.name,
            id: this.id ? this.id : "",
            scancodeSpecialPolicyItems: arr || []
          };
          if (param.scancodeSpecialPolicyItems.length == 0) {
            this.$Message.error("请至少选择一个经销商!");
            this.btnDisabled = false;
            return;
          }

          this.$jsonPost(url, param)
            .then(data => {
              this.$Notice.success({
                title: `${text}成功`
              });
              this.$router.push({
                name: "policy/bunch/list",
                query: {
                  currentPage: this.list.currentPage,
                  pageSize: this.list.pageSize
                }
              });
            })
            .catch(() => {
              this.btnDisabled = false;
            });
        } else {
          this.btnDisabled = false;
        }
      });
    },
    cancle() {
      this.$router.back();
    },
    jumpPrevPage() {
      this.$router.push("/policy/bunch/list");
    }
  }
};
</script>
<style scoped>
 /deep/ .ivu-input-icon{
  right:50px;
}
</style>